const path = process.cwd()
    fs = require('fs'),
    prog = null,
    args = null,
    config = null;

function help(){
    console.log('cs cd -a/--add [path] [aliasName]');
}

function changePath(){
    let configData = fs.readFileSync(__dirname+'/../config/cd.conf','utf8');
    try {
        configData = JSON.parse(configData);
    } catch(e) {
        console.log('config has been broken,create new one');
        configData = {};
    }
    const cmd = `${configData[args[0]]}`;
    process.chdir(cmd)
    console.log(process.cwd())
    // const result = exec(cmd, (err, stdout, stderr) => {
    //     if (err) {
    //         console.error(e)
    //     } else {
    //        console.log(stdout);
    //     }
    // });

    // result.on('exit', (code, signal) => {

    // });
}

function write(data){
    fs.writeFile(__dirname+'/../config/cd.conf',data,function(e){
        if(e){throw e}
    });
}

function add(){
    const exists = fs.existsSync(prog.add);
    if(!exists){
        let data = {};
        data[args[0]] = prog.add;
        write(JSON.stringify(data));
    }else{
        let configData = fs.readFileSync(__dirname+'/../config/cd.conf','utf8');
        try {
            configData = JSON.parse(configData);
        } catch(e) {
            console.log('config has been broken,create new one');
            configData = {};
        }
        configData[args[0]] = prog.add;
        write(JSON.stringify(configData));
    }
}

module.exports = function(program){
    prog = program;
    args = prog.args;
    if(prog.add){
        if(args.length<1){
            console.error('path and aliasName is required');
        }else{
            add();
        }
    }else{
        changePath();
    }
}